package com.hsy.swueasspider.utils

import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
import com.hsy.swueasspider.TAG
import com.hsy.swueasspider.ui.SwuEasSpiderActivity

object SwuEasCookieUtils {
    private const val SP_COOKIE = "spCookie"

    fun writeCookie(context: Context) {
        val sp = context.getSharedPreferences(SP_COOKIE, Context.MODE_PRIVATE)
        val cookie = SwuEasSpiderUtils.getCurrentCookie(context)
        if (cookie.isEmpty()) return
        sp.edit()
            .putString("Cookie", cookie)
            .apply()
    }

    fun readCookie(context: Context) {
        val sp = context.getSharedPreferences(SP_COOKIE, Context.MODE_PRIVATE)
        val cookie = sp.getString("Cookie", "") ?: ""
        SwuEasSpiderUtils.setCurrentCookie(cookie)
        Log.v(TAG, "read -> $cookie")
    }

    fun ensureCookieUsable(
        context: Context,
        username: String,
        password: String,
        doGetData: (String) -> Unit
    ) {
        val cookie = SwuEasSpiderUtils.getCurrentCookie(context)
        if (cookie.isNotEmpty()) {
            doGetData.invoke(cookie)
        } else {
            val getCookieIntent = Intent(context, SwuEasSpiderActivity::class.java)
                .putExtra(SwuEasSpiderActivity.MODE, SwuEasSpiderActivity.MODE_GET_COOKIE)
                .putExtra(SwuEasSpiderActivity.USERNAME, username)
                .putExtra(SwuEasSpiderActivity.PASSWORD, password)
            context.startActivity(getCookieIntent)
        }
    }
}